require 'libxml'

class MarcconverterController < ApplicationController
  
  def convert
    require 'MarcTools'
    rismid="000072450"
        dn ='dn:http://www.loc.gov/MARC21/slim'
        xml_document = LibXML::XML::Document.file('/home/stephan/RSQV/cz.xml')
        if params["extext"]
          rismid=params["extext"]["name"]
        end
   
          
          
        book_xpath = '//dn:record/dn:controlfield[@tag="001"][contains(.,"'+rismid+'")]/..'
        @ids=xml_document.find('//dn:record/dn:controlfield[@tag="001"]/text()',dn).to_a.shuffle[0..6]
  
               
    @old_xml=xml_document.find(book_xpath,dn)[0]

    converter=MarcTools::MarcConverter.new
    @marc_hash=converter.marc_to_hash(@old_xml)
@marc_hash=converter.updateElements(@marc_hash,'031$a', lambda { |a| a[1..-1]})
@marc_hash=converter.updateElements(@marc_hash,'031$b', lambda { |a| a[1..-1]})
@marc_hash=converter.updateElements(@marc_hash,'031$c', lambda { |a| a[1..-1]})
@marc_hash=converter.updateElements(@marc_hash,'100$a', lambda { |a|  a[-1]==',' ?   a[0..-2] :  a})
@marc_hash=converter.updateElements(@marc_hash,'700$a', lambda  { |a|  a[-1]==',' ?   a[0..-2] :  a})
@marc_hash=converter.updateElements(@marc_hash,'240$a', lambda { |a|  a[-1]==',' ?   a[0..-2] :  a})
@marc_hash=converter.changeTag(@marc_hash,'246', '730') 
@marc_hash=converter.changeTag(@marc_hash,'080', '500')
@marc_hash=converter.changeTag(@marc_hash,'910', '852')
@marc_hash=converter.insertTag(@marc_hash,'852$a', 'CZ-Bu')

@marc_hash=converter.concat(@marc_hash,'500$2','500$a')

@marc_hash=converter.changeSubfieldCode(@marc_hash,'500$2','500$a')
@marc_hash=converter.filter(@marc_hash, %w[ 031$2 100$7 655$2 008 007 100$4 500$2 650$2 700$7 ])
    @new_xml=converter.hash_to_marc(@marc_hash)
  end

  
  
end

